package com.Jin.controller;

import com.Jin.exception.BusinessException;
import com.Jin.exception.SqlException;
import com.Jin.exception.SystemException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


@RestControllerAdvice
public class ExceptionAdvice {

    //处理系统异常
    @ExceptionHandler(SystemException.class)
    public Result handSystemException(SystemException e){
        //记录日志
        //发送消息给运维
        //发送邮件给开发,包括e的异常对象
        System.out.println("出现系统异常："+e);
        return new Result(e.getCode(),e.getMessage(),e);
    }

    //处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Result handBusinessException(BusinessException e){
        System.out.println("出现业务异常："+e);
        return new Result(e.getCode(),e.getMessage(),e);
    }


    //处理账号重复异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handSqlException(SQLIntegrityConstraintViolationException e){
        System.out.println("出现SQL重复异常: "+e);
        return new Result(Code.SQL_REPEAT,e.getMessage(),e);
    }


    //处理空参数异常NullPointerException
    @ExceptionHandler(NullPointerException.class)
    public Result handSqlException(NullPointerException e){
        System.out.println("出现SQL空指针异常: "+e);
        return new Result(Code.SQL_NULLPOINT,"请将必填信息填写完整！",e);
    }

    //处理sql其他异常
    @ExceptionHandler(SqlException.class)
    public Result handSqlException(SqlException e){
        System.out.println("出现SQL异常: "+e);
        return new Result(Code.SQL_ERR,e.getMessage(),e);
    }

    //处理未知异常
    @ExceptionHandler(Exception.class)
    public Result handException(Exception e){
        System.out.println("出现未知异常："+e);
        return new Result(Code.SYSTEM_UNKNOWN_ERR,"系统繁忙，请稍后再试！",e);
    }

}
